module.exports = ngModule => {
  ngModule.factory('mainFactory', function ($q, $resource, $native, Config) {

    var list = [];
    var pageNum = 1;
    var hasNextPage = true;

    var resource = $resource(Config.api.stocks, {}, {
      query: {
        method: 'post',
        headers: $native.packageHeaders(),
        params: {
          pageNum: '@pageNum',
          pageSize: '@pageSize',
          stocks: '@stocks'
        },
        timeout: Config.timeout
      }
    });

    return {
      refresh: function (stocks) {
        var defer = $q.defer();  //声明延后执行
        resource.query({
          pageNum: 1,
          pageSize: Config.pageSize,
          stocks: stocks
        }, function (response) {
          if (response.info != undefined) {
            pageNum = 0;
            pageNum = response.info.pageNum;
            hasNextPage = true;
            list = response.info.list;
            if (response.info.list < Config.pageSize) {
              hasNextPage = false;
            }
            defer.resolve(list); //声明执行成功
          } else {
            defer.resolve(list); //声明执行成功
          }
        }, function (error) {
          defer.reject(error); //声明执行失败
        });
        return defer.promise; //返回承诺，返回获取数据的API
      },
      loadMore: function (stocks) {
        if (list === undefined) {
          return false;
        }
        var defer = $q.defer();  //声明延后执行
        resource.query({
          pageNum: pageNum,
          pageSize: Config.pageSize,
          stocks: stocks
        }, function (response) {
          pageNum = response.info.pageNum;
          if (response.info.list.length < Config.pageSize) {
            hasNextPage = false;
          }
          list = list.concat(response.info.list);
          defer.resolve(list); //声明执行成功
        }, function (error) {
          defer.reject(error); //声明执行失败
        });
        return defer.promise; //返回承诺，返回获取数据的API
      },
      hasNextPage: function () {
        return hasNextPage;
      }
    };


  });
};
